package com.cabinet.web.controller;

import java.io.File;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.cabinet.base.util.DateUtil;
import com.cabinet.base.util.PageUtils;
import com.cabinet.easy.util.Page;
import com.cabinet.service.ICoClassService;
import com.cabinet.service.IMCommoditiesService;
import com.cabinet.service.dto.CommoditiesDto;
import com.cabinet.service.dto.CommoditiesPageUtil;
import com.cabinet.web.entity.Coclass;
import com.cabinet.web.entity.Commodities;
import com.cabinet.web.entity.Seller;
import com.github.miemiedev.mybatis.paginator.domain.PageList;
import com.github.miemiedev.mybatis.paginator.domain.Paginator;

import cn.com.cabinet.service.CommoditiesServiceImpl;
import cn.com.cabinet.service.SellerServiceImpl;
import cn.com.easy.dto.MessageDTO;
import cn.com.easy.dto.PageRequestParamDTO;
import cn.com.easy.utils.CookieUtils;
import cn.com.easy.utils.ResponseOutputUtils;

@Controller
@RequestMapping("/seller/commodities")
public class CommoditiesUploadController {
	
	
	@Autowired
	private IMCommoditiesService imCommoditiesService;
	
	@Autowired
	private SellerServiceImpl sellerServiceImpl;
	
	@Autowired
	private CommoditiesServiceImpl commoditiesServiceImpl;
	
	@Autowired
	private ICoClassService iCoClassService;
	
	@RequestMapping("/upload/index")
	public String redirectCommodities(ModelMap modelMap){
		List<Coclass> coclassList= iCoClassService.getCoclass();
		modelMap.addAttribute("coclassList", coclassList);
		return "/uploadCommodities/index";
		
	}
	
	
	@RequestMapping("/list")
	public void getCommodities(HttpServletRequest req, HttpServletResponse res, PageRequestParamDTO paramDto, String key, Long status) throws Exception{
		
		String pfCount = CookieUtils.getCookieValue(req, "pfCount");
		Seller s = sellerServiceImpl.getSellerBysAccount(pfCount);
		System.out.println("System.out.println(key):"+key);
		System.out.println("System.out.println(status):"+status);
		
		int thispage = (paramDto.getPageNumber()-1)*10;
		CommoditiesPageUtil commoditiesPage = new CommoditiesPageUtil();
		commoditiesPage.setPage(thispage);
		commoditiesPage.setLimit(paramDto.getPageSize());
		commoditiesPage.setSellerId(s.getId());
		if(status == 0){
			commoditiesPage.setStatus(null);
		}else{
			commoditiesPage.setStatus(status);
		}
		if(key == "" || key.equals("")){
			commoditiesPage.setKey(null);
		}else{
			commoditiesPage.setKey(key);
		}
		
		List<CommoditiesDto> commodities = imCommoditiesService.queryCommoditiesBySellerId(commoditiesPage);
		
		int totalcount = imCommoditiesService.queryCommoditiesCountBySellerId(commoditiesPage);
		Paginator p = new Paginator(thispage, paramDto.getPageSize(), totalcount);
		PageList<CommoditiesDto> pageObject = new PageList<>(commodities, p);
		Page<CommoditiesDto> page = PageUtils.getPage(pageObject);
		
		ResponseOutputUtils.renderJson(res, MessageDTO.newInstance("", true, page));
	}

	
	@RequestMapping("/submit")
	public String applicationSubmit(HttpServletRequest req,MultipartFile ICardFile,Long coClassId,String coName,Integer coNum,
			String coPrice) throws Exception{
		System.out.println(coPrice);
		String pfCount = CookieUtils.getCookieValue(req, "pfCount");
		Seller s = sellerServiceImpl.getSellerBysAccount(pfCount);		 
		String fileName = uploadResume(ICardFile,DateUtil.DateNum());
		Commodities c = new Commodities();
		c.setCoClassId(coClassId);
		c.setCoName(coName);
		c.setCoNum(coNum);
		c.setCoPhoto("upload/cabinet/commpodities/"+fileName);
		c.setCoPrice(coPrice);
		c.setSellerId(s.getId());
		commoditiesServiceImpl.addCommodities(c);
		
	
		return "redirect:/seller/commodities/upload/index";
		
	}
	
	
	@RequestMapping("/getList")
	@ResponseBody
	public List<Commodities> getCommoditiesList(HttpServletRequest req, HttpServletResponse res) throws Exception{
		String pfCount = CookieUtils.getCookieValue(req, "pfCount");
		Seller s = sellerServiceImpl.getSellerBysAccount(pfCount);
		return commoditiesServiceImpl.getCommoditiesList(s.getId());
		
	}
	
	@RequestMapping("/getone")
	@ResponseBody
	public Commodities getCommoties(Long id){
		return commoditiesServiceImpl.getCommodities(id);
		
	}
	
	/**
	 * 用户上传文件
	 */
	public String uploadResume(MultipartFile resumeFile,String fileName){
		

		if(resumeFile!=null){
	   		// 原始文件名称
	        String resumeFile_name =  resumeFile.getOriginalFilename();
	        if(resumeFile_name!=null && resumeFile_name.trim().length()>0){
	    	   // 用户简历文件名设置为      用户id-用户名-职位名-简历（保证了唯一，而且上传新的会覆盖掉原来的）
	            String newFileName =  fileName + resumeFile_name.substring(resumeFile_name.lastIndexOf("."));
	            //上传图片  上传到当前项目路径下的uppload文件夹下
	            String path = "/opt/upload/cabinet/commpodities";
	            File uploadPic = new File(path+ "/" +newFileName);
	            if(!uploadPic.exists()){
	                uploadPic.mkdirs();
	            }
	            
	            //向磁盘写文件
	            try {
	            	resumeFile.transferTo(uploadPic);
				} catch (Exception e) {
					e.printStackTrace();
				}
	            return newFileName;
	          
	        }
		}
			return null;
	}
}
